package org.headquarter.persistance;

import java.io.File;

import org.headquarter.object.Node;
import org.headquarter.object.UnicId;
import org.simpleDom.DomManager;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class FileSystemNodeRepository implements NodePersister{

    File localNodeRepositoryFolder;

    public FileSystemNodeRepository(String folderPath){
	localNodeRepositoryFolder = new File(folderPath);

    }

    @Override
    public Node load(UnicId id) throws LoadError {
	Node result = null;
	Document doc =DomManager.loadFile(getFileForUnidId(id));
	if(doc!=null){
	    Element e = doc.getDocumentElement();
	    String type = e.getAttribute("type");
	    if(type!=null&&type.length()>0){
		ClassLoader cl = FileSystemNodeRepository.class.getClassLoader();
		try {
		    Class c = cl.loadClass(type);
		    result = (Node)c.newInstance();
		    result.loadXml(e);
		} catch (InstantiationException e1) {
		    throw new LoadError();
		} catch (IllegalAccessException e1) {
		    throw new LoadError();
		} catch (ClassNotFoundException e1) {
		    throw new LoadError();
		}
	    }else{
		throw new LoadError();
	    }
	}
	return result;
    }

    @Override
    public void save(Node node) throws SaveError {

	if(node.getUnicId()==null){
	    UnicId newId;
	    newId = new UnicId();
	    File f = new File(getFileForUnidId(newId));
	    while(f.exists()){
		newId = new UnicId();
		f = new File(getFileForUnidId(newId));
	    }
	    node.setUnicId(newId);
	}
	org.w3c.dom.Document doc = DomManager.createEmptyDocument();
	doc.appendChild(node.toXml(doc));
	DomManager.saveDocument(doc, getFileForUnidId(node.getUnicId()));
    }


    String getFileForUnidId(UnicId newId){
	return localNodeRepositoryFolder.getAbsolutePath()+"/"+newId.toString()+".xml";
    }

    @Override
    public void deleteNode(UnicId id) {
	// TODO Auto-generated method stub

    }


}
